import { cityApi } from "@/utils/api";

// 城市模块
const cityModule = {
  // 表示命名空间
  // 不只有state需要加模块名称，getters/mutations/actions也都需要去添加模块名称了
  namespaced: true,
  state: {
    cityName: localStorage.getItem("city") || "北京",
    cityId: +localStorage.getItem("id") || 110100,
    // 城市选择列表数据
    cityList: [],
  },
  getters: {
    // 通过城市列表，计算出热门城市和其他城市
    hotCitys(state) {
      return state.cityList[0];
    },
    otherCitys(state) {
      return state.cityList.slice(1);
    },
  },
  mutations: {
    changeCity(state, payload) {
      state.cityName = payload.name;
      state.cityId = payload.id;
    },
    // 改变城市列表
    getCity(state, payload) {
      state.cityList = payload.result;
    },
  },
  actions: {
    // 城市列表的数据请求
    async getCityListAsync({ commit }) {
      const res = await cityApi();
      commit("getCity", res);
    },
  },
};

export default cityModule;
